package com.mr3chi.horoscopes;

import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.select.Elements;

import com.facebook.FacebookException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.Session;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.widget.FacebookDialog;
import com.facebook.widget.WebDialog;
import com.facebook.widget.WebDialog.OnCompleteListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.mr3chi.horoscopes.R;
import com.roomorama.caldroid.CaldroidFragment;
import com.roomorama.caldroid.CaldroidListener;
import com.todddavies.components.progressbar.ProgressWheel;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.support.v7.app.ActionBarActivity;

public class ActivityHoroscopeDetail extends ActionBarActivity {
	public static String ARG_NAME 		= "name_info";
    private String horoName;

    TextView tvTitle;
    TextView tvDate;
    TextView tvContent;
    
    private NewsHoroTask 	task = null;
    
    private ProgressWheel 	mLoadBar;
    private LinearLayout 	mContent;
    
    private Bundle state;
    private Date selectedDate;
    private CaldroidFragment dialogCaldroidFragment;
    final CaldroidListener listener = new CaldroidListener() {
		@Override
		public void onSelectDate(Date date, View view) {
			if(dialogCaldroidFragment != null && dialogCaldroidFragment.isVisible()){
				selectedDate = date;
				dialogCaldroidFragment.dismiss();
				parseSelectedDay();
			}
		}
	};
	
	private UiLifecycleHelper uiHelper;
	private StatusCallback callback = new StatusCallback() {
	    @Override
	    public void call(Session session, SessionState state, Exception exception) {
	        onSessionStateChange(session, state, exception);
	    }
	};
	
	private void onSessionStateChange(final Session session, SessionState state, Exception exception) {
	    if (state.isOpened()) {
//	    	Request request = Request.newMeRequest(session, 
//	    	        new Request.GraphUserCallback() {
//	    	    @Override
//	    	    public void onCompleted(GraphUser user, Response response) {
//	    	        // If the response is successful
//	    	        if (session == Session.getActiveSession()) {
//	    	            if (user != null) {
//	    	                welcome.setText("Hi " + user.getName());  
//	    	            }
//	    	        }
//	    	       
//	    	    }
//	    	});
//	    	request.executeAsync();
	    } else if (state.isClosed()) {
	    }
	}
 
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_horoscope_detail);
		
		uiHelper = new UiLifecycleHelper(this, callback);
	    uiHelper.onCreate(savedInstanceState);
       
		Bundle b = this.getIntent().getExtras();
		horoName = b.getString(ARG_NAME);	
		
		Calendar c = Calendar.getInstance(); 
		selectedDate = c.getTime();
		state = savedInstanceState;
		
		ImageView ivTop = (ImageView) findViewById(R.id.activity_detail_top_image);
		ivTop.setImageBitmap(LoadIcon(horoName));
		TextView tvTopTitle = (TextView) findViewById(R.id.activity_detail_top_title);
		tvTopTitle.setText(horoName);
		TextView tvTopDesc = (TextView) findViewById(R.id.activity_detail_top_desc);
		tvTopDesc.setText(loadTime(horoName));
		
		tvTitle = (TextView) findViewById(R.id.activity_detail_news_title);
	    tvDate = (TextView) findViewById(R.id.activity_detail_news_date);
	    tvContent = (TextView) findViewById(R.id.activity_detail_news_desc);
	    
	    mContent = (LinearLayout) findViewById(R.id.activity_detail_info);
	    mLoadBar = (ProgressWheel) findViewById(R.id.activity_detail_loader);
		mLoadBar.spin();
		
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setHomeButtonEnabled(true);
        parseSelectedDay();   
        
        AdView adView = (AdView)findViewById(R.id.adView);
		AdRequest adRequest = new AdRequest.Builder().build();
		adView.loadAd(adRequest);
	}

	@Override
	protected void onPause() {
		super.onPause();
		uiHelper.onPause();
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		uiHelper.onResume();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		uiHelper.onDestroy();
	}

	public void setLoading(boolean load){
		if(load){
			if(mLoadBar.getVisibility()==View.VISIBLE) return;
			else{
				mLoadBar.setVisibility(View.VISIBLE);
				mContent.setVisibility(View.GONE);
				mLoadBar.spin();
			}
		}else{
			if(mLoadBar.getVisibility()==View.GONE) return;
			else{
				mLoadBar.setVisibility(View.GONE);
				mContent.setVisibility(View.VISIBLE);
				mLoadBar.stopSpinning();
			}
		}
	}

	@Override
	protected void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		uiHelper.onSaveInstanceState(outState);
		
		if (dialogCaldroidFragment != null) {
			dialogCaldroidFragment.saveStatesToKey(outState, "DIALOG_CALDROID_SAVED_STATE");
		}

	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		uiHelper.onActivityResult(requestCode, resultCode, data);
	}
	
	public void parseSelectedDay() {
		if(hasConnection()){
			if(loadNewsHoroFromDB()){
				setLoading(false);
				return;
			}
			setLoading(true);
	        task = new NewsHoroTask();
	        task.execute((Void) null);
        } else {
        	if(!loadNewsHoroFromDB()){
        		Toast.makeText(this, R.string.error_nonew_here_yet, Toast.LENGTH_SHORT).show();
        		setLoading(false);
        		mContent.setVisibility(View.GONE);
        	}else{
        		setLoading(false);
        		mContent.setVisibility(View.VISIBLE);
        	}
        	
        }
	}

	public String loadTime(String s) {
		String horoTime = "";
		if(s==""){
		}
		else if(s.equalsIgnoreCase("Aries"))
			horoTime="21/3 - 20/4";
		else if(s.equalsIgnoreCase("Taurus"))
			horoTime="21/4 - 21/5";
		else if(s.equalsIgnoreCase("Gemini"))
			horoTime="22/5 - 21/6";
		else if(s.equalsIgnoreCase("Cancer"))
			horoTime="22/6 - 22/7";
		else if(s.equalsIgnoreCase("Leo"))
			horoTime="23/7 - 22/8";
		else if(s.equalsIgnoreCase("Virgo"))
			horoTime="23/8 - 23/9";
		else if(s.equalsIgnoreCase("Libra"))
			horoTime="24/9 - 23/10";
		else if(s.equalsIgnoreCase("Scorpio"))
			horoTime="24/10 - 22/11";
		else if(s.equalsIgnoreCase("Sagittarius"))
			horoTime="23/11 - 21/12";
		else if(s.equalsIgnoreCase("Capricorn"))
			horoTime="22/12 - 20/1";
		else if(s.equalsIgnoreCase("Aquarius"))
			horoTime="21/1 - 19/2";
		else if(s.equalsIgnoreCase("Pisces"))
			horoTime="20/2 - 20/3";
		return horoTime;
	}
	
	public Bitmap LoadIcon(String s) {
		if(s=="")
			return null;
		else if(s.equalsIgnoreCase("Aries"))
			return BitmapFactory.decodeResource(this.getResources(), R.drawable.p1_aries);
		else if(s.equalsIgnoreCase("Taurus"))
			return BitmapFactory.decodeResource(this.getResources(), R.drawable.p2_taurus);
		else if(s.equalsIgnoreCase("Gemini"))
			return BitmapFactory.decodeResource(this.getResources(), R.drawable.p3_gemini);
		else if(s.equalsIgnoreCase("Cancer"))
			return BitmapFactory.decodeResource(this.getResources(), R.drawable.p4_cancer);
		else if(s.equalsIgnoreCase("Leo"))
			return BitmapFactory.decodeResource(this.getResources(), R.drawable.p5_leo);
		else if(s.equalsIgnoreCase("Virgo"))
			return BitmapFactory.decodeResource(this.getResources(), R.drawable.p6_virgo);
		else if(s.equalsIgnoreCase("Libra"))
			return BitmapFactory.decodeResource(this.getResources(), R.drawable.p7_libra);
		else if(s.equalsIgnoreCase("Scorpio"))
			return BitmapFactory.decodeResource(this.getResources(), R.drawable.p8_scorpio);
		else if(s.equalsIgnoreCase("Sagittarius"))
			return BitmapFactory.decodeResource(this.getResources(), R.drawable.p9_sagittarius);
		else if(s.equalsIgnoreCase("Capricorn"))
			return BitmapFactory.decodeResource(this.getResources(), R.drawable.p10_capricorn);
		else if(s.equalsIgnoreCase("Aquarius"))
			return BitmapFactory.decodeResource(this.getResources(), R.drawable.p11_aquarius);
		else if(s.equalsIgnoreCase("Pisces"))
			return BitmapFactory.decodeResource(this.getResources(), R.drawable.p12_pisces);
		return null;
			
	}
	
	public boolean hasConnection() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo wifiNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        if (wifiNetwork != null && wifiNetwork.isConnected()) {
          return true;
        }
        NetworkInfo mobileNetwork = cm.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
        if (mobileNetwork != null && mobileNetwork.isConnected()) {
          return true;
        }
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        if (activeNetwork != null && activeNetwork.isConnected()) {
          return true;
        }
        return false;
    }
	
	public boolean loadNewsHoroFromDB(){
		DBAdapter db = new DBAdapter(getApplicationContext());
		db.open();
		boolean rs = false;
		List<NewsHoroscope> allNews = db.getAllHorosByHoroNameAndDate(horoName, NewsHoroscope.getStringFromDate(selectedDate));
		if(allNews != null && allNews.size() > 0 && !allNews.get(0).getContent().trim().equals("")){
			tvTitle.setText("Daily Horoscope");
			tvDate.setText("In " + allNews.get(0).getShowOffString());
			tvContent.setText(allNews.get(0).getContent());
			rs = true;
		}
		db.close();
		return rs;
	}
	
	public void saveNewsHoroToDB(NewsHoroscope item){
		NewsHoroscope temp = item;
		DBAdapter db = new DBAdapter(getApplicationContext());
		db.open();
		List<NewsHoroscope> list = db.getAllHorosByHoroNameAndDate(horoName, item.getDateString());
		if(list != null && list.size()>0){
			
			temp.setId(list.get(0).getId());
			db.updateHoroById(temp);
			
			for(int i = 1; i < list.size();i++){
				db.deleteHoroById(list.get(i).getId());
			}
		}else{
			db.insertHoro(item);
		}
		db.close();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.menu_horoscope_detail, menu);
        return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch(item.getItemId()){
		case R.id.activity_detail_changedate:	
			dialogCaldroidFragment = new CaldroidFragment();
			dialogCaldroidFragment.setCaldroidListener(listener);
			
			final String dialogTag = "CALDROID_DIALOG_FRAGMENT";
			if (state != null) {
				dialogCaldroidFragment.restoreDialogStatesFromKey(getSupportFragmentManager(), 
						state, "DIALOG_CALDROID_SAVED_STATE", dialogTag);
				Bundle args = dialogCaldroidFragment.getArguments();
				if (args == null) {
					args = new Bundle();
					dialogCaldroidFragment.setArguments(args);
				}
			} else {
				Bundle bundle = new Bundle();
				dialogCaldroidFragment.setArguments(bundle);
			}
			ArrayList<Date> ignoreDay = new ArrayList<Date>();
			ignoreDay.add(selectedDate);
			dialogCaldroidFragment.setDisableDates(ignoreDay);
			dialogCaldroidFragment.show(getSupportFragmentManager(), dialogTag);
			
			DBAdapter db = new DBAdapter(this);
			db.open();
			
			List<NewsHoroscope> list = db.getAllHorosByHoroName(horoName);
			if(list != null){
				for(int i = 0; i<list.size();i++){
					dialogCaldroidFragment.setBackgroundResourceForDate(R.color.datepicker_background_color, list.get(i).getDate());
					dialogCaldroidFragment.setTextColorForDate(R.color.datepicker_text_color, list.get(i).getDate());
				}
			}
			db.close();
			
			return true;
		case R.id.activity_detail_refresh:
			parseSelectedDay();
			return true;
		case R.id.activity_detail_sharefb:
			if(hasConnection()){
				if(tvContent.getVisibility() == View.GONE || tvContent.getText().toString().trim().equals("")){
					Toast.makeText(this, R.string.error_feed_share_nothing, Toast.LENGTH_SHORT).show();
				}else{
					if(FacebookDialog.canPresentShareDialog(this, FacebookDialog.ShareDialogFeature.SHARE_DIALOG)){
						showShareDialog();
						
					}else{
						Session session = Session.getActiveSession();
			            if (session != null && session.isOpened()) {
			            	showFeedDialog(); 
			            	 
			            }else{
			            	Toast.makeText(this, R.string.error_session_failed, Toast.LENGTH_SHORT).show();
			            }
					}
				}
				
			}else{
				Toast.makeText(this, R.string.error_no_intenet_connection, Toast.LENGTH_SHORT).show();
			}
			return true;
		case R.id.activity_detail_shareothers:
			String shareBody = tvContent.getText().toString();
			if(tvContent.getVisibility() == View.GONE || tvContent.getText().toString().trim().equals("")){
				Toast.makeText(this, R.string.error_feed_share_nothing, Toast.LENGTH_SHORT).show();
			}else{
				Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
		        sharingIntent.setType("text/plain");
		        sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Horoscope");
		        sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
		        startActivity(Intent.createChooser(sharingIntent, getResources().getString(R.string.sharing_others_caption)));
			}
			return true;
		default:
			return false;
		}
	}
	
	private void showFeedDialog(){
	    WebDialog feedDialog = (new WebDialog.FeedDialogBuilder(this, Session.getActiveSession()))
	    		.setLink("www.google.com")
	    		.setPicture(getResources().getString(R.string.sharing_image_link))
	    		.setName(getResources().getString(R.string.sharing_title))
	    		.setCaption(tvContent.getText().toString())
	    		//.setDescription(tvContent.getText().toString())
	    		.setOnCompleteListener(new OnCompleteListener() {		

					@Override
					public void onComplete(Bundle values,
							FacebookException error) {
						if(error == null){
							final String postId = values.getString("post_id");
		                    if (postId != null) {
		                        Toast.makeText(ActivityHoroscopeDetail.this, R.string.error_feed_share_ok, Toast.LENGTH_SHORT).show();
		                    }else {
		                        //Toast.makeText(ActivityHoroscopeDetail.this,  "Publish cancelled", Toast.LENGTH_SHORT).show();
		                    }
						}else if (error instanceof FacebookOperationCanceledException) {
		                    //Toast.makeText(ActivityHoroscopeDetail.this, "Publish cancelled", Toast.LENGTH_SHORT).show();
		                } else {
		                    Toast.makeText(ActivityHoroscopeDetail.this, R.string.error_feed_share_fail, Toast.LENGTH_SHORT).show();
		                }
					}
				}).build();
	    feedDialog.show();
	
	}
	
	private void showShareDialog(){
		
		FacebookDialog shareDialog = new FacebookDialog.ShareDialogBuilder(this)
		.setLink("www.google.com")
		.setPicture(getResources().getString(R.string.sharing_image_link))
		.setName(getResources().getString(R.string.sharing_title))
		.setCaption(tvContent.getText().toString())
		
        .build();
		uiHelper.trackPendingDialogCall(shareDialog.present());
	}
	
	private int getIdFromName(String name){
		int i = 0;
		
		if(name.equals("Aries")){
			i = 1;
		}else if(name.equals("Taurus")){
			i = 2;
		}else if(name.equals("Gemini")){
			i = 3;
		}else if(name.equals("Cancer")){
			i = 4;
		}else if(name.equals("Leo")){
			i = 5;
		}else if(name.equals("Virgo")){
			i = 6;
		}else if(name.equals("Libra")){
			i = 7;
		}else if(name.equals("Scorpio")){
			i = 8;
		}else if(name.equals("Sagittarius")){
			i = 9;
		}else if(name.equals("Capricorn")){
			i = 10;
		}else if(name.equals("Aquarius")){
			i = 11;
		}else if(name.equals("Pisces")){
			i = 12;
		}
		
		return i;
	}

	private class NewsHoroTask extends AsyncTask<Void, Void, String>{
		
		public NewsHoroTask() {
			
		}
    
		@Override
		protected String doInBackground(Void... params) {
			int index = getIdFromName(horoName);
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd",Locale.US);
			String date = sdf.format(selectedDate);
			String ur = "http://m.dailyhoroscope.com/free-daily-horoscope/?date=" + date +"&sign=" + index;
			Document doc;
			try {
				URL url = new URL(ur);
				doc = Jsoup.parse(url.openStream(),"UTF-8",ur);
				
				Elements nodes = doc.select("div.scope");
				if(nodes != null && nodes.size() > 0){
					String rs = nodes.first().text();
					Log.e("done done", rs);
					return rs;
				}else{
					Log.e(" not not done done", "sd");
				}
	    		
			} catch (IOException e) {
			}
			return null;
		}

		@Override
		protected void onCancelled() {
			super.onCancelled();
			setLoading(false);
			task = null;
		}

		@Override
		protected void onPostExecute(String item) {
			super.onPostExecute(item);
			if(item == null){
				Toast.makeText(getBaseContext(),R.string.error_no_horoscope, Toast.LENGTH_SHORT).show();
				setLoading(false);
				
				return;
			}
			
			if(!item.trim().equals("")){
				saveNewsHoroToDB(new NewsHoroscope(horoName, selectedDate, item));
			}
			
			if(!loadNewsHoroFromDB()){
        		Toast.makeText(ActivityHoroscopeDetail.this, R.string.error_nonew_here_yet, Toast.LENGTH_SHORT).show();
        		setLoading(false);
        		mContent.setVisibility(View.GONE);
        	}else{
        		setLoading(false);
        		if(mContent.getVisibility() != View.VISIBLE) mContent.setVisibility(View.VISIBLE);
        	}
			
		}
	}
	
}
